﻿using Control.Enum;
using Control.Server;
using Control.Server.Message;

using System;
using System.Drawing.Imaging;
using System.Linq;
using System.Security.Cryptography;

using TouchSocket.Core;
using TouchSocket.Http.WebSockets;

namespace Control.WeSocket
{
    public class WebSocketPlugin : PluginBase, IWebSocketReceivedPlugin
    {
        private CancellationTokenSource? _cancellationTokenSource;

        // 声明一个该委托类型的字段
        public Form1.UpdateImageDelegate? UpdateImageHandler { get; set; }

        public async Task OnWebSocketReceived(IWebSocket webSocket, WSDataFrameEventArgs e)
        {

            switch (e.DataFrame.Opcode)
            {
                case WSDataType.Text:
                    {

                    }
                    break;
                case WSDataType.Binary:
                    {
                        Console.WriteLine("收到二进制数据");
                        using (var byteBlock = e.DataFrame.PayloadData)
                        {
                            byte[]? byteMemory = byteBlock.Memory.ToArray();
                          
                            
                            // 使用委托调用 UpdateImage 方法
                            UpdateImageHandler?.Invoke(byteMemory);

                        }

                    }
                    break;
                case WSDataType.Ping:
                    {
                        Console.WriteLine("收到Ping");
                    }
                    break;
                case WSDataType.Pong:
                    {
                        Console.WriteLine("收到Pong");
                    }
                    break;
                case WSDataType.Close:
                    {
                        _cancellationTokenSource?.Cancel();
                        Console.WriteLine("收到Close");
                    }
                    break;
            }
            await e.InvokeNext();
        }

        private byte[] BitmapToByteArray(Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }

    }
}
